<?php
namespace app\beautiful\logic\printer;
use app\common\helper\printer\feie\FeiePrinter;
use app\common\helper\printer\Yly\YlyPrinter;
use app\common\model\ShopModel;
use app\beautiful\model\PrinterModel;
use app\beautiful\model\setting\PrinterAppModel;

class PrinterLogic {
    protected $shopId;
    protected $shop;
    protected $setting;
    public function __construct($shopId)
    {
       try{
           if(null === $shop = ShopModel::find($shopId)) $this->error('商铺不存在');
           $this->shopId=$shopId;
           $this->shop=$shop;

           //判断配置
           if(null === $setting = PrinterAppModel::where([
                   ['shop_id','=',$shopId],
                   ['is_delete','=',0]
               ])->find()){
               $this->error('未配置设置');
           }
           $this->setting=$setting->toArray();
       } catch (\Exception $e){

       }
    }

    public function print($type,$id)
    {

        try{
            $printers=$this->getPrinterList($type);
            foreach ($printers as $printer){
                if($printer->app_type=='yly'){
                    $ContentLogic=new PrinterYlyContentLogic();
                    $content=$ContentLogic->$type($this->shop,$id);
                    $YlyPrinter=new YlyPrinter($this->setting);
                    $YlyPrinter->printMsg($printer->machine_code,$content);
                }else{
                    $FeiePrinter = new FeiePrinter($this->setting);
                    $ContentLogic=new PrinterFeieContentLogic();
                    $content=$ContentLogic->$type($this->shop,$id);
                    $FeiePrinter->printMsg($printer->print_sn,$content);
                }
            }
        }catch (\Exception $e){
            wyuLog('printer.txt',$e->getMessage());
        }
        return true;
    }

    protected function getPrinterList($type)
    {
        $printers=PrinterModel::where([
            ['shop_id','=',$this->shopId],
        ])->whereRaw(" FIND_IN_SET('{$type}',jurisdiction)")
            ->select();
        return $printers;
    }

    public function error($message){
        throw new \Exception($message);
    }
}
